using Audio;
using DG.Tweening;
using System.Collections;
using UI.ExamplePanel;
using UnityEngine;
using UnityEngine.UI;

public enum State
{
    InitState,
    AttackState,
    ExitAttack
}

public class CoreMechanismManager : Singleton<CoreMechanismManager>
{
    public State currentState;

    public int canGiveCardNum;

    private Guest currentGuest;

    private int curGuestIndex = 0;

    private bool isTransitioning = false; // 防止重复触发

    // 过渡动画初始化数据
    Image dark;
    Tween fadeTween;

    private void Start()
    {
        dark = GamePanel.Instance.dark;
        dark.gameObject.SetActive(true);
        dark.color = new Color(0, 0, 0, 0);
        //CoroutineManager.Instance.AddTask(EnterGuest());
    }



  /// <summary>
  /// 开始游戏流程,进入guest
  /// </summary>
  /// <returns></returns>
    public IEnumerator EnterGuest()
    {
        SetState(State.InitState);

        currentGuest = GuestManager.Instance.GetGuest(curGuestIndex);
        GamePanel.Instance.UpdateGuestUI(currentGuest);
        GamePanel.Instance.DoGuestAnimation();
        Debug.Log($"第 {curGuestIndex} 位顾客入场：{currentGuest.name}");

        switch (GameManager.Instance.curState)
        {
            case GameState.FirstTurn:



                break;

            case GameState.SecondTurn:

                GamePanel.Instance.ShowGuest(false);
                AudioManager.Instance.PauseBGM();
                if(curGuestIndex == 1)
                {
                    DialogManager.Instance.StartDialogueForCharacter("铃铛1", 0, GamePanel.Instance.transform, true);
                    while (!DialogManager.Instance.isDialogEnd)
                    {
                        yield return null;
                    }
                    AudioManager.Instance.ManagerMusic("Rouge", true);
                }
                else if(curGuestIndex == 2)
                {
                    DialogManager.Instance.StartDialogueForCharacter("铃铛2", 0, GamePanel.Instance.transform, true);
                    while (!DialogManager.Instance.isDialogEnd)
                    {
                        yield return null;
                    }
                    AudioManager.Instance.ManagerMusic("V", true);
                }

                break;
        }

        // 进入出牌阶段
        GamePanel.Instance.ShowGuest(true);
        isTransitioning = false;
        yield return EnterAttackPhase();
    }


    private IEnumerator EnterAttackPhase()  // 出牌阶段
    {
        //TODO：添加自动结束和回合结算
        SetState(State.AttackState);
        bool endTurnPressed = false;
        GamePanel.Instance.endTurn.onClick.AddListener(() => endTurnPressed = true);        // 绑定“结束回合”按钮

        var curGameState = GameManager.Instance.curState;
        int curGuestTurn = currentGuest.GetCurrentGuestTurn();
        int maxGuestTurn = currentGuest.GetCurStateMaxTurn(curGameState);

        CardManager.Instance.ClearAllCards();
        CardManager.Instance.BuildDeck(GameManager.Instance.FristStateDeck);

        while (curGuestTurn < maxGuestTurn && currentState == State.AttackState)
        {
            endTurnPressed = false;
            curGuestTurn = currentGuest.SetGuestTurn();
            Debug.Log($"开始第 {curGuestTurn} 回合");

            canGiveCardNum = SetCanGiveCardNum();
            GamePanel.Instance.UpdateAttackTurnUI(curGuestTurn, canGiveCardNum);

            //计算可抽卡的数量
            int curBarData = currentGuest.GetBarData(false);
            int getNum = 5 - Mathf.Min(3, Mathf.Abs(curBarData) / 25);
            Debug.Log($"心境为{curBarData},本回合能抽{getNum}张卡");

            // 抽卡
            CardManager.Instance.DrawCards(getNum);

            switch (GameManager.Instance.curState)
            {
                case GameState.FirstTurn:


                    break;

                case GameState.SecondTurn:


                    break;
            }

            // 等待总回合结束
            yield return new WaitUntil(() => endTurnPressed || currentState != State.AttackState);

            Debug.Log($"第 {curGuestTurn} 回合结束");

            // 这里可以添加小回合结束时的处理逻辑

            yield return null; // 确保一帧结束
        }

        GamePanel.Instance.endTurn.onClick.RemoveAllListeners();
        CardManager.Instance.ClearAllCards();

        // 顾客退场
        yield return ExitGuest();
    }


    public IEnumerator ExitGuest()          // 顾客退场
    {
        switch (GameManager.Instance.curState)
        {
            case GameState.FirstTurn:

                //guest的结束对话
                DialogManager.Instance.StartDialogueForCharacter(currentGuest.name, 0, GamePanel.Instance.transform);
                while (!DialogManager.Instance.isDialogEnd)
                {
                    yield return null;
                }

                break;

            case GameState.SecondTurn:

                //感谢？

                //感谢完后，前一位顾客退场后，要触发下一位顾客的故事场景
                if (curGuestIndex == 0)
                {
                    currentGuest = GuestManager.Instance.EnterNextGuest(ref curGuestIndex);  //提前切换，不然下一次还是上一次的角色入场
                    GamePanel.Instance.HideMe();
                    BlackPanel.Instance.ShowMe();
                    BlackPanel.Instance.ToNextPanel<SelectSpecialCardPanel>();
                    CardManager.Instance.ResetAttackCount();
                    AudioManager.Instance.ManagerMusic("V", true);
                    yield break;
                }
                break;
        }

        currentGuest.SetGuestTurn(true);    //Reset
        SetState(State.ExitAttack);
        Debug.Log("顾客退场中...");

        yield return NextGuest();
    }


    public IEnumerator NextGuest()          // 结算该阶段数据，判断切换下一个顾客
    {
        currentGuest = GuestManager.Instance.EnterNextGuest(ref curGuestIndex);  //在这里切换下一个guest，并且判断是否还有顾客
        if (currentGuest == null)
        {
            Debug.Log("已经没有顾客了！该流程结算。");

            //切换结束流程
            switch (GameManager.Instance.curState)
            {
                case GameState.FirstTurn:

                    GamePanel.Instance.ShowGuest(false);
                    DialogManager.Instance.StartDialogueForCharacter("铃铛", 0, GamePanel.Instance.transform, true);
                    while (!DialogManager.Instance.isDialogEnd)
                    {
                        yield return null;
                    }

                    //结束对话后，进入第二阶段的开始
                    curGuestIndex = 0;
                    GamePanel.Instance.HideMe();
                    BlackPanel.Instance.ShowMe();
                    BlackPanel.Instance.ToNextPanel<SelectSpecialCardPanel>();
                    CardManager.Instance.ResetAttackCount();

                    GameManager.Instance.SwitchGameState(GameState.SecondTurn); //切换阶段
                    AudioManager.Instance.ManagerMusic("Rouge", true);                  

                    yield break;


                case GameState.SecondTurn:

                    GameOverPanel.Instance.ShowMe();
                    AudioManager.Instance.ManagerMusic("Main", true);

                    break;
            }

            yield break;
        }

        Debug.Log("进入下一个顾客");

        //动画
        fadeTween = dark.DOFade(1f, 1f).SetEase(Ease.OutQuad);
        yield return fadeTween.WaitForCompletion();
        dark.DOFade(0f, 1f).SetEase(Ease.OutQuad).WaitForCompletion();

        CoroutineManager.Instance.AddTask(EnterGuest());
        CoroutineManager.Instance.Finish();
        yield return null;
    }


    public void SetState(State targetState)
    {
        currentState = targetState;
    }

    /// <summary>
    /// 获取当前游戏流程中当前的角色
    /// </summary>
    /// <returns></returns>
    public Guest GetCurrentGuest()
    {
        return currentGuest;
    }

    /// <summary>
    /// 设置该回合可打出卡牌的数量
    /// </summary>
    /// <returns></returns>
    public int SetCanGiveCardNum()
    {
        int curPower = currentGuest.GetBarData(true);
        Debug.Log($"能量为{curPower},本回合只能出{ 2 + Mathf.Min(3, Mathf.Abs(curPower) / 25)}张卡");
        return 2 + Mathf.Min(3, Mathf.Abs(curPower) / 25);
    }
}